package com.pig4cloud.pigx.contract.api.v1.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.customize.api.enums.AbnormalEnum;
import com.pig4cloud.pigx.common.customize.api.util.OpenApiUtil;
import com.pig4cloud.pigx.contract.api.v1.service.PositionMarginDetailServiceV1;
import com.pig4cloud.pigx.contract.entity.ContractPositionMarginDetail;
import com.pig4cloud.pigx.contract.mapper.ContractPositionMarginDetailMapper;
import com.pig4cloud.pigx.contract.open.api.vo.OpenApiPositionMarginDetailVOV1;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

/**
 */
@Service
@AllArgsConstructor
public class PositionMarginDetailServiceImplV1 extends ServiceImpl<ContractPositionMarginDetailMapper, ContractPositionMarginDetail> implements PositionMarginDetailServiceV1 {

	@Override
	public R<List<OpenApiPositionMarginDetailVOV1>> getList(Long positionId) {
		// 必填校验
		if (positionId == null) {
			throw OpenApiUtil.getError(AbnormalEnum.MSG.MANDATORY_PARAM_EMPTY_OR_MALFORMED, "positionId");
		}
		try {
			List<ContractPositionMarginDetail> details = baseMapper.selectList(new QueryWrapper<ContractPositionMarginDetail>() {{
				eq("position_id", positionId);
				orderByDesc("create_time");
			}});

			List<OpenApiPositionMarginDetailVOV1> voList = new ArrayList<>();
			details.forEach(e -> {
				OpenApiPositionMarginDetailVOV1 vo = new OpenApiPositionMarginDetailVOV1();
				BeanUtils.copyProperties(e, vo);
				vo.setTime(e.getCreateTime().toInstant(ZoneOffset.ofHours(8)).toEpochMilli());
				if ("0".equals(vo.getOperationType())) {
					vo.setOperationType("增加");
				}
				if ("1".equals(vo.getOperationType())) {
					vo.setOperationType("减少");
				}
				voList.add(vo);
			});
			return R.ok(voList);
		} catch (Exception e) {
			throw OpenApiUtil.getError(AbnormalEnum.MSG.DISCONNECTED);
		}
	}

}
